package com.example.controller;

import com.example.service.AwaitTerminationExampleService;
import com.example.service.ForkJoinPoolApiService;
import com.example.service.ForkJoinPoolExampleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

@RestController
@RequestMapping("/fork/join/pool/example")
public class ForkJoinPoolExampleController {

    @Autowired
    private ForkJoinPoolExampleService forkJoinPoolExampleService;
    @Autowired
    private ForkJoinPoolApiService forkJoinPoolApiService;
    @Autowired
    private AwaitTerminationExampleService awaitTerminationExampleService;

    @GetMapping("/forkjoin-example")
    public String executeForkJoinTask() {
        forkJoinPoolExampleService.executeForkJoinTask();
        return "ForkJoinPool 示例任务已启动";
    }

    @GetMapping("/invoke-task")
    public String executeTaskWithInvoke() {
        int result = forkJoinPoolApiService.executeTaskWithInvoke();
        return "任务结果: " + result;
    }

    @GetMapping("/submit-task")
    public String executeTaskWithSubmit() throws ExecutionException, InterruptedException {
        Future<Integer> future = forkJoinPoolApiService.executeTaskWithSubmit();
        return "任务结果: " + future.get();  // 阻塞等待任务结果
    }

    @GetMapping("/execute-task")
    public String executeTaskWithoutWaiting() {
        forkJoinPoolApiService.executeTaskWithoutWaiting();
        return "任务已提交，未等待结果";
    }

    @GetMapping("/shutdown-forkjoin")
    public String shutdownForkJoinPool() {
        forkJoinPoolApiService.shutdownForkJoinPool();
        return "ForkJoinPool 已关闭";
    }

    @GetMapping("/await-termination-example")
    public String executeAwaitTerminationTask() {
        awaitTerminationExampleService.executeTasksWithTermination();
        return "AwaitTermination 示例任务已启动";
    }
}
